`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date: 2024/02/24 20:47:25
// Design Name: 
// Module Name: LED
// Project Name: 
// Target Devices: 
// Tool Versions: 
// Description: 
// 
// Dependencies: 
// 
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// 
//////////////////////////////////////////////////////////////////////////////////


module flow_LED_FSM(Clk,Rst_n,LED);
//定义状态空间
	input Clk;
	input Rst_n;
	
	output reg [3:0] LED;
	
	reg [3:0] c_state;
	reg [3:0] n_state;
	reg [19:0] Cnt;
	reg flag;
	
	localparam
		LED_0 = 4'b0001,
		LED_1 = 4'b0010,
		LED_2 = 4'b0100,
		LED_3 = 4'b1000;

always@(posedge Clk or negedge Rst_n)begin
		if(!Rst_n)
			Cnt <= 20'b0;
		else if(Cnt == 20'd999_999)begin  //20ms
			Cnt <= 20'd0;
			flag = ~flag;
			end
		else
			Cnt <= Cnt+1'b1;
	end
	
//状态跳转
always@(posedge flag or negedge Rst_n)begin
	if(!Rst_n)
		c_state <= LED_0;
	else
		c_state <= n_state;
end 

//下个状态判断
always@(*)begin
	n_state = LED_0;
	case(c_state)
	  LED_0:begin if(Rst_n) n_state<=LED_1;else n_state<=LED_0;end
     LED_1:begin if(Rst_n) n_state<=LED_2;else n_state<=LED_0;end
     LED_2:begin if(Rst_n) n_state<=LED_3;else n_state<=LED_0;end
     LED_3:begin if(Rst_n) n_state<=LED_0;else n_state<=LED_0;end
     default: n_state<=LED_0;	
	endcase
end

//各个状态下的动作
always@(c_state)begin
		case(c_state)
			LED_0:LED <= 4'b1110;
			LED_1:LED <= 4'b1101;
			LED_2:LED <= 4'b1011;
			LED_3:LED <= 4'b0111;
			default:LED <= 4'b1110;
		endcase
end

endmodule 